package org.linlinjava.litemall.wx.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.notify.AwsNotifyService;
import org.linlinjava.litemall.core.notify.NoticeHelper;
import org.linlinjava.litemall.core.payment.DefaultCurType;
import org.linlinjava.litemall.core.payment.PaymentResponseCode;
import org.linlinjava.litemall.core.payment.paypal.config.PaypalPaymentIntent;
import org.linlinjava.litemall.core.payment.paypal.config.PaypalPaymentMethod;
import org.linlinjava.litemall.core.payment.paypal.config.PaypalPaymentState;
import org.linlinjava.litemall.core.payment.paypal.service.impl.CardPaypalServiceImpl;
import org.linlinjava.litemall.core.util.AdminCouponDateUtil;
import org.linlinjava.litemall.core.util.GeneratorUtil;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.wx.dto.BuyGiveeMemberDTO;
import org.linlinjava.litemall.wx.dto.GiftCardBuyMemberDTO;
import org.linlinjava.litemall.wx.manage.WxPayMemberUserManageService;
import org.linlinjava.litemall.wx.util.PageUtil;
import org.linlinjava.litemall.wx.vo.OrderVo;
import org.linlinjava.litemall.wx.vo.PayMemberUserLogVo;
import org.linlinjava.litemall.wx.vo.PayMemberWelfareVo;
import org.linlinjava.litemall.wx.vo.WxPayMemberVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static org.linlinjava.litemall.db.beans.Constants.*;
import static org.linlinjava.litemall.wx.util.WxResponseCode.*;

/**
 * wx支付会员用户服务
 *
 * @author yliyun
 * @date 2022/09/15
 */
@Service
public class WxPayMemberUserService {
    /**
     * 日志记录器
     */
    private final Log logger = LogFactory.getLog(CardPaypalServiceImpl.class);

    /**
     * api上下文
     */
    @Autowired
    private APIContext apiContext;

    /**
     * 成功url
     */
    @Value("${member.paypal.suceess}")
    private String successUrl;
    /**
     * 取消url
     */
    @Value("${member.paypal.cancel}")
    private String cancelUrl;

    /**
     * 卢米埃支付会员用户服务
     */
    @Autowired
    private LumierePayMemberUserService lumierePayMemberUserService;

    /**
     * 卢米埃支付会员服务
     */
    @Autowired
    private LumierePayMemberService lumierePayMemberService;

    @Autowired
    private LumiereCouponStrategyService lumiereCouponStrategyService;

    @Autowired
    private LumiereCouponUserService lumiereCouponUserService;

    /**
     * 卢米埃成员福利优惠服务
     */
    @Autowired
    private LumiereMemberWelfareCouponService lumiereMemberWelfareCouponService;

    /**
     * 卢米埃成员福利订阅服务
     */
    @Autowired
    private LumiereMemberWelfareSubscribeService lumiereMemberWelfareSubscribeService;

    /**
     * litemall优惠券服务
     */
    @Autowired
    private LitemallCouponService litemallCouponService;

    /**
     * litemall礼品卡服务
     */
    @Autowired
    private LitemallGiftCardService litemallGiftCardService;

    /**
     * litemall礼品卡用户服务
     */
    @Autowired
    private LitemallGiftCardUserService litemallGiftCardUserService;

    /**
     * 卢米埃订阅服务
     */
    @Autowired
    private LumiereSubscribeService lumiereSubscribeService;

    /**
     * 卢米埃支付会员用户日志服务
     */
    @Autowired
    private LumierePayMemberUserLogService lumierePayMemberUserLogService;

    /**
     * litemall用户服务
     */
    @Autowired
    private LitemallUserService litemallUserService;

    /**
     * litemall优惠券用户服务
     */
    @Autowired
    private LitemallCouponUserService litemallCouponUserService;

    /**
     * 卢米埃订阅用户服务
     */
    @Autowired
    private LumiereSubscribeUserService lumiereSubscribeUserService;

    /**
     * 卢米埃订阅规则服务
     */
    @Autowired
    private LumiereSubscribeRuleService lumiereSubscribeRuleService;

    /**
     * 订单服务
     */
    @Autowired
    private LitemallOrderService orderService;

    @Autowired
    private LitemallRechargeConsumptionService litemallRechargeConsumptionService;

    /**
     * 地区服务
     */
    @Autowired
    private LitemallRegionService regionService;

    /**
     * litemall店地区服务
     */
    @Autowired
    private LitemallShopRegionService litemallShopRegionService;

    /**
     * 完整日志服务
     */
    @Autowired
    private LitemallIntegralLogService integralLogService;


    /**
     * 注意助手
     */
    @Autowired
    private NoticeHelper noticeHelper;

    /**
     * aws通知服务
     */
    @Autowired
    private AwsNotifyService awsNotifyService;


    @Autowired
    private WxPayMemberUserManageService wxPayMemberUserManageService;


    /**
     * 由用户支付成员列表
     *
     * @param userId 用户id
     * @param shopId 商店id
     * @return {@link Object}
     */
    public Object listPayMemberByUser(Integer userId, Integer shopId) {

        LumierePayMemberExample example = new LumierePayMemberExample();
        example.or().andStatusEqualTo(Constants.MEMBER_STATUS_INUSE);
        List<LumierePayMember> members = lumierePayMemberService.list(example);

        //门店Id
        if (shopId != null) {

            Integer cityRegionId = getShopRegionId(shopId);
            members = members.stream().filter(member -> {
                if(member.getShopIds() != null){
                    for (int i = 0; i < member.getShopIds().length; i++) {
                        if (member.getShopIds()[i].equals(cityRegionId)) {
                            return true;
                        }
                    }
                    return false;
                }else{
                    return true;
                }
            }).collect(Collectors.toList());
        }

        List<WxPayMemberVo> vos = members.stream().map(member -> {
            WxPayMemberVo vo = new WxPayMemberVo();
            BeanUtils.copyProperties(member, vo);
            List<LumierePayMemberUser> users = lumierePayMemberUserService.listUsers(userId, member.getId());
            if (users.size() == 0) {
                vo.setIsBuy((byte) 0);
            } else {
                vo.setEndTime(users.get(0).getEndTime().toLocalDate().toString());
                vo.setIsBuy((byte) 1);
            }

            return vo;
        }).sorted(Comparator.comparing(WxPayMemberVo::getIsBuy).reversed()).collect(Collectors.toList());
        return ResponseUtil.okList(vos);
    }

    /**
     * 付费会员细节
     *
     * @param userId      用户id
     * @param payMemberId 付费会员id
     * @return {@link Object}
     */
    public Object payMemberDetail(Integer userId, Integer payMemberId) {
        WxPayMemberVo wxPayMemberVo = new WxPayMemberVo();
        LumierePayMember payMember = lumierePayMemberService.findById(payMemberId);
        BeanUtils.copyProperties(payMember, wxPayMemberVo);

        //查询优惠券信息
        List<PayMemberWelfareVo> welfareVos = new ArrayList<>();
        List<LumiereCouponStrategy> couponStrategies = lumiereCouponStrategyService.list(Wrappers.lambdaQuery(LumiereCouponStrategy.class)
                .eq(LumiereCouponStrategy::getCouponType,6)
                .like(LumiereCouponStrategy::getPayMember, payMemberId));
        if(couponStrategies!=null&&couponStrategies.size()>0){
            couponStrategies.stream().forEach(coupon -> {
                PayMemberWelfareVo vo = new PayMemberWelfareVo();
                vo.setWelfareName(coupon.getName());
                vo.setNumbers(coupon.getReleasedQuantity());
                vo.setType(1);
                welfareVos.add(vo);
            });
        }


        //查询礼物卡信息
        if (payMember.getGiftCardIds() != null) {
            Integer[] giftCardIds = payMember.getGiftCardIds();
            if (giftCardIds.length > 0) {
                for (int i = 0; i < giftCardIds.length; i++) {
                    LitemallGiftCard giftCard = litemallGiftCardService.findById(giftCardIds[i]);
                    PayMemberWelfareVo vo = new PayMemberWelfareVo();
                    if (giftCard != null) {
                        vo.setWelfareName(giftCard.getName());
                        vo.setNumbers(1);
                        vo.setType(3);
                        welfareVos.add(vo);
                    }
                }
            }
        }

        //查询订阅信息
        Map<Integer, List<LumiereMemberWelfareSubscribe>> welfareSubscribes =
                lumiereMemberWelfareSubscribeService.findByMemberId(payMemberId, (byte) 2)
                        .stream().collect(Collectors.groupingBy(LumiereMemberWelfareSubscribe::getSubscribeId));

        welfareSubscribes.keySet().forEach(key -> {
            LumiereSubscribe subscribe = lumiereSubscribeService.findById(key);

            PayMemberWelfareVo vo = new PayMemberWelfareVo();
            if (subscribe != null) {
                vo.setWelfareName(subscribe.getName());
                vo.setNumbers(1);
                vo.setType(2);
                welfareVos.add(vo);
            }
        });

        //查询区域信息
        Integer[] regionIds = payMember.getShopIds();
        List<String> regions = new ArrayList<>();
        if(regionIds != null && regionIds.length > 0){
            regions =  regionService.findByIds(Arrays.asList(regionIds)).stream().map(LitemallRegion::getNameEn).collect(Collectors.toList());
        }
        wxPayMemberVo.setRegionNames(regions);
        wxPayMemberVo.setWelfareVos(welfareVos);
        List<LumierePayMemberUser> payMemberUsers = lumierePayMemberUserService.listUsers(userId, payMemberId);
        wxPayMemberVo.setIsBuy(payMemberUsers.size() > 0 ? (byte) 1 : (byte) 0);
        wxPayMemberVo.setDicountPer(wxPayMemberVo.getDicountPer() != null ? wxPayMemberVo.getDicountPer().divide(new BigDecimal(100)).setScale(2) : null);
        return ResponseUtil.ok(wxPayMemberVo);
    }

    /**
     * 付费会员日志
     *
     * @param userId       用户id
     * @param purchaseType 购买类型
     * @param page         页面
     * @param limit        限制
     * @param sort         排序
     * @param order        订单
     * @return {@link Object}
     */
    public Object payMemberLog(Integer userId, Integer purchaseType,
                               Integer page,Integer limit,
                               String sort,String order) {
        LitemallUser user = litemallUserService.findById(userId);
        Integer type = purchaseType;       //1--购买，3--赠送

        //赠送 2--送给别人，3--别人赠送
        if (purchaseType == 2 || purchaseType == 3) {
            type = 3;
        }
        List<PayMemberUserLogVo> vos = new ArrayList<>();
        if (type == 1) {                   //自己购买
            LumierePayMemberUserLogExample example = new LumierePayMemberUserLogExample();
            example.or().andUserIdEqualTo(userId).andPurchaseIdEqualTo(userId);

            if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
                example.setOrderByClause(sort + " " + order);
            }
            List<LumierePayMemberUserLog> logs = lumierePayMemberUserLogService.list(example);

            vos = logs.stream().map(log -> {
                LumierePayMember payMember = lumierePayMemberService.findById(log.getPayMemberId());
                PayMemberUserLogVo vo = new PayMemberUserLogVo();
                vo.setPayType(log.getPayType());
                vo.setPurchaser(user != null ? user.getUsername() : null);
                vo.setBuyTime(log.getAddTime().toString());
                vo.setPrice(log.getPrice());
                vo.setPoints(log.getPoint());
                vo.setPayMemberName(log.getPayMemberName());
                vo.setExpiredTime(log.getExpiredTime() != null ? log.getExpiredTime().toString() : null);

                if(log.getExpiredTime() != null && log.getExpiredTime().isBefore(LocalDateTime.now())){
                    vo.setIsExpired(true);
                }else{
                    vo.setIsExpired(false);
                }

                vo.setPictrue(payMember.getPicUrl());
                return vo;
            }).collect(Collectors.toList());
        } else {
            if (purchaseType == 2) {       //被赠记录
                LumierePayMemberUserLogExample example = new LumierePayMemberUserLogExample();
                example.or().andUserIdEqualTo(userId);
                List<LumierePayMemberUserLog> logs = lumierePayMemberUserLogService.list(example);

                vos = logs.stream().filter(l -> {
                    if (l.getUserId().equals(l.getPurchaseId()) == false) {
                        return true;
                    } else {
                        return false;
                    }
                }).map(log -> {
                    LumierePayMember payMember = lumierePayMemberService.findById(log.getPayMemberId());
                    PayMemberUserLogVo vo = new PayMemberUserLogVo();
                    vo.setPayType(log.getPayType());
                    vo.setBuyTime(log.getAddTime().toString());
                    vo.setPrice(log.getPrice());
                    vo.setPayMemberName(log.getPayMemberName());
                    vo.setExpiredTime(log.getExpiredTime() != null ? log.getExpiredTime().toString() : null);

                    if (log.getUserId() != null) {
                        LitemallUser giveeUser = litemallUserService.findById(log.getPurchaseId());
                        vo.setPurchaser(giveeUser.getUsername());
                    }
                    vo.setPictrue(payMember.getPicUrl());
                    vo.setPoints(log.getPoint());
                    if(log.getExpiredTime() != null && log.getExpiredTime().isBefore(LocalDateTime.now())){
                        vo.setIsExpired(true);
                    }else{
                        vo.setIsExpired(false);
                    }
                    return vo;
                }).collect(Collectors.toList());
            } else {
                //找出所有但购买者PurchaseId与UserId不同的记录 （不相同则是赠送记录）
                List<LumierePayMemberUserLog> logs = lumierePayMemberUserLogService.list(Wrappers.lambdaQuery(LumierePayMemberUserLog.class)
                        .eq(LumierePayMemberUserLog::getPurchaseId,userId)
                );

                vos = logs.stream()
                        //挑出 赠送者id等于当前用户和被赠送者名字不为空的  或者 赠送者id等于当前用户和被赠送id不等于当前用户id的
                        .filter(log->(log.getPurchaseName()!=null&&!(userId.equals(log.getUserId())))||(log.getPurchaseName()==null&&!(userId.equals(log.getPurchaseName()))))
                        .map(log -> {
                            LumierePayMember payMember = lumierePayMemberService.findById(log.getPayMemberId());

                            PayMemberUserLogVo vo = new PayMemberUserLogVo();
                            vo.setPayType(log.getPayType());
                            vo.setBuyTime(log.getAddTime().toString());
                            vo.setPrice(log.getPrice());
                            vo.setPayMemberName(log.getPayMemberName());
                            vo.setExpiredTime(log.getAddTime() != null ? log.getAddTime().toString() : null);
                            if (log.getPurchaseId() != null) {
                                LitemallUser giveeUser = litemallUserService.findById(log.getUserId());
                                vo.setPurchaser(ObjectUtil.isEmpty(giveeUser)?log.getPurchaseName():giveeUser.getUsername());
                            }
                            if(log.getExpiredTime() != null && log.getExpiredTime().isBefore(LocalDateTime.now())){
                                vo.setIsExpired(true);
                            }else{
                                vo.setIsExpired(false);
                            }
                            vo.setPoints(log.getPoint());
                            vo.setPictrue(payMember.getPicUrl());
                            return vo;
                        }).collect(Collectors.toList());
            }
        }
        vos = vos.stream().sorted(Comparator.comparing(PayMemberUserLogVo::getExpiredTime)).collect(Collectors.toList());
        Collections.reverse(vos);
        Pageable pageable = PageRequest.of(page - 1,limit);
        return ResponseUtil.ok(PageUtil.getPageLumierePayMemberUserLogVo(pageable,vos));
    }

    /**
     * 订单支付成员
     *
     * @param userId   用户id
     * @param memberId 成员身份
     * @param point    点
     * @param givee    givee
     * @return {@link Object}
     */
    public Object orderPayMemberByPoint(Integer userId, Integer memberId, BigDecimal point, String givee) {

        //查一下有没有这个付费会员
        LumierePayMember payMember = lumierePayMemberService.findById(memberId);
        //没有不可购买
        if (payMember == null) {
            return Constants.MEMBER_EXCEPTION_NULL;
        }

        //查改用户
        LitemallUser user = litemallUserService.findById(userId);
        //判断积分是否充足
        if (user.getPoints().compareTo(point) < 0) {
            return Constants.NOT_ENOUGH_POINT;
        }

        //有被赠送人
        if (givee != null && givee != "") {
            LitemallUser giveeUser = litemallUserService.queryMobileOrEmail(givee);

            if (giveeUser != null) {    //赠送用户已存在
                List<LumierePayMemberUser> users = lumierePayMemberUserService.listUsers(giveeUser.getId(), memberId);

                if (users.size() > 0) {
                    if (payMember.getIsSupportReneval() == true && payMember.getRenevalPoint() != null) {
                        if (point.compareTo(payMember.getRenevalPoint()) != 0) {
                            return Constants.NOT_EQUALS_RENEVAL_POINT;
                        } else {
                            return Constants.MEMBER_SUCCESS;
                        }
                    } else {
                        return Constants.NOT_SUPPORT_RENEVAL_POINT;
                    }
                } else {
                    if (payMember.getPoint() != null) {
                        if (point.compareTo(payMember.getPoint()) != 0) {
                            return Constants.NOT_EQUALS_POINT;
                        } else {
                            return Constants.MEMBER_SUCCESS;
                        }
                    } else {
                        return Constants.NOT_SUPPORT_POINT;
                    }
                }
            } else {                    //赠送用户不存在
                List<LumierePayMemberUser> users = lumierePayMemberUserService.listByUserName(givee, memberId);
                if (users.size() > 0) {   //用户还没有注册，但是已经有人赠送了会员，需要注册完成后自动领取
                    return Constants.NOT_REGISTER;
                } else {
                    if (payMember.getPoint() != null) {
                        if (point.compareTo(payMember.getPoint()) != 0) {
                            return Constants.NOT_EQUALS_POINT;
                        } else {
                            return Constants.MEMBER_SUCCESS;
                        }
                    } else {
                        return Constants.NOT_SUPPORT_POINT;
                    }
                }
            }
        }
        return Constants.MEMBER_SUCCESS;
    }

    /**
     * 订单支付会员钱
     *
     * @param userId   用户id
     * @param memberId 成员身份
     * @param money    钱
     * @param givee    givee
     * @return {@link Object}
     */
    public Object orderPayMemberByMoney(Integer userId, Integer memberId, BigDecimal money, String givee) {
        //查一下有没有这个付费会员
        LumierePayMember payMember = lumierePayMemberService.findById(memberId);
        //付费会员不存在
        if (payMember == null) {
            return Constants.MEMBER_EXCEPTION_NULL;
        }

        if (givee != null && givee != "") {
            LitemallUser giveeUser = litemallUserService.queryMobileOrEmail(givee);

            if (giveeUser != null) {    //赠送用户已存在
                List<LumierePayMemberUser> users = lumierePayMemberUserService.listUsers(giveeUser.getId(), memberId);

                if (users.size() > 0) {
                    if (payMember.getIsSupportReneval() == true && payMember.getRenevalMoney() != null) {
                        if (money.compareTo(payMember.getRenevalMoney()) != 0) {
                            return Constants.NOT_EQUALS_RENEVAL_MONEY;
                        } else {
                            return Constants.MEMBER_SUCCESS;
                        }
                    } else {
                        return Constants.NOT_SUPPORT_RENEVAL_MONEY;
                    }
                } else {
                    if (payMember.getMoney() != null) {
                        if (money.compareTo(payMember.getMoney()) != 0) {
                            return Constants.NOT_EQUALS_MONEY;
                        } else {
                            return Constants.MEMBER_SUCCESS;
                        }
                    } else {
                        return Constants.NOT_SUPPORT_MONEY;
                    }
                }
            } else {                    //赠送用户不存在
                List<LumierePayMemberUser> users = lumierePayMemberUserService.listByUserName(givee, memberId);

                if (users.size() > 0) {   //用户还没有注册，但是已经有人赠送了会员，需要注册完成后自动领取
                    return Constants.NOT_REGISTER;
                } else {
                    if (payMember.getMoney() != null) {
                        if (money.compareTo(payMember.getMoney()) != 0) {
                            return Constants.NOT_EQUALS_MONEY;
                        } else {
                            return Constants.MEMBER_SUCCESS;
                        }
                    } else {
                        return Constants.NOT_SUPPORT_MONEY;
                    }
                }
            }
        } else {

            LitemallUser user = litemallUserService.findById(userId);
            if (user != null) {
                List<LumierePayMemberUser> users = lumierePayMemberUserService.listUsers(user.getId(), memberId);

                if (users.size() > 0) {
                    if (payMember.getIsSupportReneval() == true && payMember.getRenevalMoney() != null) {
                        if (money.compareTo(payMember.getRenevalMoney()) != 0) {
                            return Constants.NOT_EQUALS_RENEVAL_MONEY;
                        } else {
                            return Constants.MEMBER_SUCCESS;
                        }
                    } else {
                        return Constants.NOT_SUPPORT_RENEVAL_MONEY;
                    }
                } else {
                    if (payMember.getMoney() != null) {
                        if (money.compareTo(payMember.getMoney()) != 0) {
                            return Constants.NOT_EQUALS_MONEY;
                        } else {
                            return Constants.MEMBER_SUCCESS;
                        }
                    } else {
                        return Constants.NOT_SUPPORT_MONEY;
                    }
                }
            }
        }

        return Constants.MEMBER_SUCCESS;
    }

    /**
     * 购买会员钱
     *
     * @param memberId 成员身份
     * @param money    钱
     * @param userId   用户id
     * @param userName 用户名
     * @return {@link Object}
     */
    public Object buyMemberByMoney(Integer memberId, BigDecimal money, Integer userId, String userName) {
        LumierePayMember payMember = lumierePayMemberService.findById(memberId);
        if (payMember == null) {
            return ResponseUtil.fail(MEMBER_INVALID, "会员不存在");
        }
        //插入订单
        LitemallOrder order = new LitemallOrder();
        if (userName != null) {    //赠送
            LitemallUser user = litemallUserService.queryMobileOrEmail(userName);
            if (user != null) {
                order.setUserId(userId);
            }
        }

        order.setOrderSn(orderService.generateOrderSn(userId));
        order.setOrderStatus(Constants.ORDER_STATUS_UNPAID);
        order.setConsignee("");
        order.setMobile("");
        order.setMessage("Paypal purchase paid membership");
        order.setAddress("");
        order.setOrderPrice(money);
        order.setFreightPrice(new BigDecimal(0.00));
        order.setCouponPrice(new BigDecimal(0.00));
        order.setIntegralPrice(new BigDecimal(0.00));
        order.setOrderPrice(new BigDecimal(0.00));
        order.setActualPrice(money);
        order.setUserId(userId);
        order.setShopOrder(true);
        order.setPayMemberId(payMember.getId());
        order.setMadeStatus((byte)0);
        order.setPayType(Constants.PAY_TYPE_PAYPAL);
        // 添加订单表项
        orderService.add(order);

        OrderVo vo = new OrderVo();
        vo.setGivee(userName);
        vo.setMemberId(memberId);
        vo.setOrderId(order.getId());

        return ResponseUtil.ok(vo);
    }

    /**
     * 收到你付款
     *
     * @param orderId  订单id
     * @param givee    givee
     * @param memberId 成员身份
     * @return {@link Object}
     */
    public Object getPayment(Integer orderId, String givee, Integer memberId,String message) {
        LitemallOrder order = orderService.findById(orderId);

        if (order == null) {
            return ResponseUtil.fail(ORDER_NOT_EXIST, "订单不存在");
        }

        BigDecimal total = order.getActualPrice();
        Amount amount = new Amount();
        amount.setCurrency(DefaultCurType.CAD.getType());
        amount.setTotal(String.format("%.2f", total));

        Transaction transaction = new Transaction();
        transaction.setDescription("lumiere gift card pay");
        transaction.setAmount(amount);


        List<Transaction> transactions = new ArrayList<>();
        transactions.add(transaction);

        Payer payer = new Payer();
        payer.setPaymentMethod(PaypalPaymentMethod.paypal.toString());

        Payment payment = new Payment();
        payment.setIntent(PaypalPaymentIntent.sale.toString());
        payment.setPayer(payer);
        payment.setTransactions(transactions);
        RedirectUrls redirectUrls = new RedirectUrls();
        String sUrl = null;
        sUrl = successUrl + "?memberId=" + memberId;

        if (givee != null & givee != "") {
            sUrl += "&userName=" + givee;
        }
        redirectUrls.setCancelUrl(cancelUrl);
        redirectUrls.setReturnUrl(sUrl);
        payment.setRedirectUrls(redirectUrls);


        try {
            logger.debug("success url is " + redirectUrls.getReturnUrl());
            logger.debug("cancel url is " + redirectUrls.getCancelUrl());
            logger.debug("进入支付之前的日志");
            Payment rtn = payment.create(apiContext);
            logger.debug("进入支付页面之后的日志");
            if (null == rtn.getId() || !PaypalPaymentState.created.toString().equals(rtn.getState())) {
                return ResponseUtil.fail(PaymentResponseCode.ORDER_INVALID_OPERATION, "订单不能支付");
            }
            String paymentId = rtn.getId();
            //保存paymentId作为PayPal的商户订单号
            order.setOutTradeNo(paymentId);
            order.setMessage(message);
            orderService.updateById(order);
            return rtn;
        } catch (PayPalRESTException e) {
            e.printStackTrace();
            return ResponseUtil.fail(PaymentResponseCode.ORDER_INVALID_OPERATION, "订单不能支付");
        }
    }

    /**
     * 订单支付成功成员
     *
     * @param userId   用户id
     * @param memberId 成员身份
     * @param point    积分
     * @param givee    赠送人的账号
     * @param message  消息
     * @return {@link Object}
     */
    public Object orderPayMemberSuccess(Integer userId, Integer memberId, BigDecimal point, String givee,String message) {
        message = StrUtil.isNotEmpty(message)?message:"There's a present for you";
        LitemallUser giveeUser = null;

        LumierePayMember payMember = lumierePayMemberService.findById(memberId);

        //如有被赠送人的账号就查出来
        if (givee != null & givee != "") {
            giveeUser = litemallUserService.queryMobileOrEmail(givee);
        }

        LitemallUser user = litemallUserService.findById(userId);
        //是积分购买
        //减积分
        user.setPoints(user.getPoints().subtract(point));
        //更新一下用户积分
        litemallUserService.updateById2(user);

        //创建一个积分购买订单
        LitemallOrder order = new LitemallOrder();
        order.setUserId(userId);
        order.setOrderSn(orderService.generateOrderSn(userId));
        order.setOrderStatus(Constants.ORDER_STATUS_FINISHED);
        order.setCompleteTime(LocalDateTime.now());
        order.setConsignee("");
        order.setMobile(user.getMobile());
        order.setMessage("Bonus points for paying members");
        order.setAddress("");
        order.setPoints(point);
        order.setPayTime(LocalDateTime.now());
        order.setPayType(Constants.ORDER_PAY_TYPE_POINTS);
        order.setFreightPrice(new BigDecimal(0.00));
        order.setCouponPrice(new BigDecimal(0.00));
        order.setIntegralPrice(new BigDecimal(0.00));
        order.setOrderPrice(new BigDecimal(0.00));
        order.setActualPrice(new BigDecimal(0.00));
        order.setPayMemberId(payMember.getId());
        order.setMadeStatus((byte)0);
        orderService.add(order);

        //是赠送给别人  赠送给有账号的用户
        if (ObjectUtil.isNotNull(giveeUser)) {
            //查找被赠送人
            LumierePayMemberUserExample example = new LumierePayMemberUserExample();
            example.or().andUserIdEqualTo(giveeUser.getId()).andPayMemberIdEqualTo(memberId);
            List<LumierePayMemberUser> userList = lumierePayMemberUserService.list(example);

            //是否已拥有付费会员
            if(userList.size() != 0){
                return ResponseUtil.fail("赠送会员失败，对方已拥有");
            }
            LumierePayMemberUser memberUser = new LumierePayMemberUser();
            LocalDateTime startTime = LocalDateTime.now();
            memberUser.setStartTime(startTime);
            memberUser.setUserName(givee);
            memberUser.setPayMemberId(memberId);

            LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                endT = null;
            }
            memberUser.setEndTime(endT);
            if(payMember.getEndTime()!=null){
                memberUser.setEndTime(payMember.getEndTime());
            }
            memberUser.setAddTime(startTime);
            memberUser.setUpdateTime(startTime);

            memberUser.setUserId(giveeUser.getId());
            memberUser.setUserId(giveeUser != null ? giveeUser.getId() : null);
            memberUser.setDeleted(false);
            lumierePayMemberUserService.add(memberUser);

            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_POINT,
                    Constants.MEMBER_PURCHASE_TYPE_GIVE, null,
                    giveeUser != null ? giveeUser.getId() : 0, userId,givee,
                    memberUser.getId(), endT, point);


            logger.debug("赠送----------------------");


            LitemallIntegralLog log = new LitemallIntegralLog();
            log.setUserId(userId);
            log.setType(Constants.INTEGRAL_LOG_TYPE_MINUS);
            log.setPoints(user.getPoints());
            log.setChangePoints(point.multiply(new BigDecimal(-1)));
            //添加详细信息
            log.setUseType(4);
            log.setOrderId(order.getId());
            log.setPayMemberName(payMember.getName());
            integralLogService.add(log);

            //welfareGift(memberId, giveeUser, givee, userId, payMember, endT);
            BuyGiveeMemberDTO buyGiveeMemberDto = new BuyGiveeMemberDTO();
            buyGiveeMemberDto.setMessage(order.getMessage());
            buyGiveeMemberDto.setGiveeUser(givee);
            buyGiveeMemberDto.setMemberId(memberId);
            wxPayMemberUserManageService.sendNotificationToExistUser(giveeUser,buyGiveeMemberDto,payMember,user,memberUser,endT);
            return ResponseUtil.ok("积分会员赠送成功");
        }else if(StrUtil.isNotBlank(givee)){
            //查找被赠送人 赠送给没有账号的人
            LumierePayMemberUserExample example = new LumierePayMemberUserExample();
            example.or().andUserNameEqualTo(givee).andPayMemberIdEqualTo(memberId);
            List<LumierePayMemberUser> userList = lumierePayMemberUserService.list(example);

            //是否已拥有付费会员
            if(userList.size() != 0){
                return ResponseUtil.fail("赠送会员失败，对方已拥有");
            }
            LumierePayMemberUser memberUser = new LumierePayMemberUser();
            LocalDateTime startTime = LocalDateTime.now();
            memberUser.setStartTime(startTime);
            memberUser.setUserName(givee);
            memberUser.setPayMemberId(memberId);

            LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                endT = null;
            }
            memberUser.setEndTime(endT);
            memberUser.setAddTime(startTime);
            memberUser.setUpdateTime(startTime);

            memberUser.setUserId(null);
            memberUser.setDeleted(false);
            lumierePayMemberUserService.add(memberUser);

            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_POINT,
                    Constants.MEMBER_PURCHASE_TYPE_GIVE, null,
                    giveeUser != null ? giveeUser.getId() : 0, userId,givee,
                    memberUser.getId(), endT, point);


            logger.debug("赠送----------------------");

            LitemallIntegralLog log = new LitemallIntegralLog();
            log.setUserId(userId);
            log.setType(Constants.INTEGRAL_LOG_TYPE_MINUS);
            log.setPoints(user.getPoints());
            log.setChangePoints(point.multiply(new BigDecimal(-1)));
            //添加详细信息
            log.setUseType(4);
            log.setOrderId(order.getId());
            log.setPayMemberName(payMember.getName());
            integralLogService.add(log);

            //welfareGift(memberId, giveeUser, givee, userId, payMember, endT);
            BuyGiveeMemberDTO buyGiveeMemberDto = new BuyGiveeMemberDTO();
            buyGiveeMemberDto.setMessage(order.getMessage());
            buyGiveeMemberDto.setGiveeUser(givee);
            buyGiveeMemberDto.setMemberId(memberId);
            //发送通知
            wxPayMemberUserManageService.sendNotificationToNotExistUser(payMember,user,buyGiveeMemberDto,endT,memberUser);
            return ResponseUtil.ok("积分会员赠送成功");
        } else {
            List<LumierePayMemberUser> memberUsers = lumierePayMemberUserService.listUsers(userId, memberId);

            if (memberUsers.size() > 0) {
                LocalDateTime starT = LocalDateTime.now();
                if (memberUsers.get(0).getEndTime().compareTo(LocalDateTime.now()) < 0) {
                    starT = LocalDateTime.now();
                } else {
                    starT = memberUsers.get(0).getEndTime();
                }


                LocalDateTime eT = payMember.getExpiredDays() != null ? starT.plusDays(payMember.getExpiredDays()) : null;

                if (payMember.getExpiredDays().equals(0)) {
                    eT = null;
                }

                memberUsers.get(0).setEndTime(eT);

                logger.debug("续购-------------------------");


                LitemallIntegralLog log = new LitemallIntegralLog();
                log.setUserId(userId);
                log.setType(Constants.INTEGRAL_LOG_TYPE_MINUS);
                log.setPoints(user.getPoints());
                log.setChangePoints(point.multiply(new BigDecimal(-1)));
                //添加详细信息
                log.setUseType(4);
                log.setOrderId(order.getId());
                log.setPayMemberName(payMember.getName());
                integralLogService.add(log);
                log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_POINT,
                        Constants.MEMBER_PURCHASE_TYPE_REBUY, null,
                        userId, userId, givee,memberUsers.get(0).getId(), eT, point);
                lumierePayMemberUserService.update(memberUsers.get(0));
                return ResponseUtil.ok("积分会员续购成功");
            } else {


                LumierePayMemberUser memberUser = new LumierePayMemberUser();
                LocalDateTime startTime = LocalDateTime.now();
                memberUser.setStartTime(startTime);
                memberUser.setUserName(givee);
                memberUser.setPayMemberId(memberId);
                LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

                if (payMember.getExpiredDays().equals(0)) {
                    endT = null;
                }

                memberUser.setEndTime(endT);
                memberUser.setAddTime(startTime);
                memberUser.setUpdateTime(startTime);
                memberUser.setUserId(userId);
                memberUser.setDeleted(false);

                lumierePayMemberUserService.add(memberUser);

                logger.debug("购买------------------------------");

                LitemallIntegralLog log = new LitemallIntegralLog();
                log.setUserId(userId);
                log.setType(Constants.INTEGRAL_LOG_TYPE_MINUS);
                log.setPoints(user.getPoints());
                log.setChangePoints(point.multiply(new BigDecimal(-1)));
                //添加详细信息
                log.setUseType(4);
                log.setOrderId(order.getId());
                log.setPayMemberName(payMember.getName());
                integralLogService.add(log);
                log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_POINT,
                        Constants.MEMBER_PURCHASE_TYPE_BUY, null,
                        userId, userId,user.getUsername(), memberUser.getId(), endT, point);

                welfareGift(memberId, null, givee, userId, payMember, endT);

                String content = "Congratulations, you got "  + payMember.getName() ;

                noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, "Integral Member Gifted", content, userId, payMember);
                awsNotifyService.sendSms(MOBILE_CODE_ONE + user.getMobile(), content, org.linlinjava.litemall.db.beans.Constants.AWS_MESSAGE_TYPE_PROMOTIONAL);
                if(user.getEmail() != null ){
                    awsNotifyService.noticeMail("积分购买会员", content, content,user.getEmail() );
                }
                return ResponseUtil.ok("积分会员购买成功");
            }
        }
    }

    /**
     * 添加订阅用户
     *
     * @param userId        用户id
     * @param subscribeId   订阅id
     * @param selectRuleIds 选择规则id
     * @param endT          endt
     * @param givee         givee
     * @param giveeUser     givee用户
     * @return {@link LumiereSubscribeUser}
     */
    public LumiereSubscribeUser addSubscribeUser(Integer userId, Integer subscribeId, Integer[] selectRuleIds,
                                                 LocalDateTime endT, String givee, LitemallUser giveeUser) {

        LitemallUser user = litemallUserService.findById(userId);

        LumiereSubscribeUser lumiereSubscribeUser = new LumiereSubscribeUser();
        lumiereSubscribeUser.setPurchaserId(userId);
        if (lumiereSubscribeUser.getUserId() == null) {
            lumiereSubscribeUser.setUserId(giveeUser != null ? giveeUser.getId() : userId);
        }

        LumiereSubscribeRule rule = lumiereSubscribeRuleService.findById(selectRuleIds[0]);

        lumiereSubscribeUser.setSubscribeId(subscribeId);

        lumiereSubscribeUser.setStatus(Constants.SUBSCRIBE_USER_MEMBER_NOT_CONFIRM);

        lumiereSubscribeUser.setAutoSub(false);

        lumiereSubscribeUser.setPurchaserId(giveeUser != null ? giveeUser.getId() : userId);

        lumiereSubscribeUser.setUserName(giveeUser != null ? giveeUser.getUsername() : user != null ? user.getUsername() : null);

        lumiereSubscribeUser.setPrice(BigDecimal.ZERO);

        lumiereSubscribeUser.setStartTime(LocalDateTime.now());

        if(rule != null) {
            if (rule.getRuleType().equals((byte) 1)) {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusWeeks(1));
            } else if (rule.getRuleType().equals((byte) 2)) {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusMonths(1));
            } else {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusYears(1));
            }
        }
        lumiereSubscribeUser.setRuleId(selectRuleIds[0]);

        return lumiereSubscribeUser;
    }


    /**
     * 执行付款
     * 付款完成
     *
     * @param paymentId 支付id
     * @param payerId   付款人身份
     * @return {@link Object}
     */
    public Object executePayment(String paymentId, String payerId) {
        try {
            return executePay(paymentId, payerId);
        } catch (Exception e) {
            //支付异常，退款
            refund(paymentId);
            return ResponseUtil.fail(PaymentResponseCode.PAYMENT_FAIL, "支付失败");
        }
    }


    /**
     * 执行支付
     *
     * @param paymentId 支付id
     * @param payerId   付款人身份
     * @return {@link Object}
     * @throws PayPalRESTException 支付pal restexception
     */
    public Object executePay(String paymentId, String payerId) throws PayPalRESTException {
        Payment payment = new Payment();
        payment.setId(paymentId);
        PaymentExecution paymentExecute = new PaymentExecution();
        paymentExecute.setPayerId(payerId);
        Payment rtn = payment.execute(apiContext, paymentExecute);

        // 交易号
        String transationId = rtn.getTransactions().get(0).getRelatedResources().get(0).getSale().getId();
        if (rtn.getState().equals("approved")) {
            LitemallOrder order = orderService.findByOutTradeNo(paymentId);
            List<Transaction> transactions = rtn.getTransactions();
            BigDecimal totalFee = new BigDecimal(0.00);
            if (transactions != null) {
                for (Transaction transaction : transactions) {
                    String total = transaction.getAmount().getTotal();
                    BigDecimal b = new BigDecimal(total);
                    b.setScale(2, BigDecimal.ROUND_DOWN);
                    totalFee = totalFee.add(b);
                }
            }
            if (order == null) {
                return ResponseUtil.fail(PaymentResponseCode.ORDER_UNKNOWN, "订单不存在");
            }

            // 检查这个订单是否已经处理过
            if (order.getOrderStatus() == Constants.ORDER_STATUS_ONGOING || order.getPayId() != null) {
                return ResponseUtil.fail(PaymentResponseCode.PAYMENT_FAIL, "订单已经处理成功!");
            }

            // 检查支付订单金额
            if (!totalFee.toString().equals(order.getActualPrice().toString())) {
                return ResponseUtil.fail(PaymentResponseCode.PAYMENT_FAIL, " : 支付金额不符合 totalFee=" + totalFee);
            }

            LitemallOrder update = new LitemallOrder();
            update.setId(order.getId());
            update.setPayType(Constants.MEMBER_PAY_TYPE_PAYPAL);
            update.setCurrency(DefaultCurType.CAD.getType());
            update.setTransationId(transationId);        //交易号，退款时需要用到
            update.setPayId(payment.getId());            //付款编号，获取详情是需要用到？
            update.setPayTime(LocalDateTime.now());
            orderService.updateById2(update);

            //用户增加积分 TODO
//            List<LitemallOrderGoods> orderGoods = litemallOrderGoodsService.queryByOid(order.getId());
//            BigDecimal giveAwayPoints = new BigDecimal(0.00);
//            for(LitemallOrderGoods item : orderGoods){
//                LitemallGoods goods = goodsService.findById(item.getId());
//                if(goods.getGiveAwayPoints() != null){
//                    giveAwayPoints = giveAwayPoints.add(goods.getGiveAwayPoints().multiply(new BigDecimal(item.getNumber())));
//                }
//            }
//            if(giveAwayPoints.compareTo(new BigDecimal(0.00)) > 0){
//                LitemallUser user = userService.findById(order.getUserId());
//                if(user != null){
//                    LitemallUser litemallUser = new LitemallUser();
//                    litemallUser.setId(order.getUserId());
//                    litemallUser.setPoints(user.getPoints().add(giveAwayPoints));
//                    userService.updateById(litemallUser);
//                }
//
//            }

            return rtn;
        } else {
            return ResponseUtil.fail(PaymentResponseCode.PAYMENT_FAIL, "支付失败");
        }
    }

    /**
     * 退款
     *
     * @param orderId 订单id
     * @return boolean
     */
    public boolean refund(Integer orderId) {
        LitemallOrder order = orderService.findById(orderId);

        RefundRequest refund = new RefundRequest();
        Amount amount = new Amount();
        amount.setCurrency(order.getCurrency());
        amount.setTotal(String.format("%.2f", order.getOrderPrice()));
        refund.setAmount(amount);
//        refund.setReason(order.getDescription());


        try {
            if (StringUtils.isEmpty(order.getTransationId())) {
                //注意这段代码，获取saleId
                Payment payment = Payment.get(apiContext, order.getPayId());
                Transaction transaction = payment.getTransactions().get(0);
                RelatedResources resources = transaction.getRelatedResources().get(0);
                String id = resources.getSale().getId();
                order.setTransationId(id);
            }

            // ### Api Context
            // Pass in a `ApiContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.

            // Refund by posting to the APIService
            // using a valid AccessToken
            Sale sale = new Sale();
            sale.setId(order.getTransationId());
            DetailedRefund res = sale.refund(apiContext, refund);
            if (res.getState().equals(PaypalPaymentState.completed.toString())) {
                return true;
            }
            return false;
        } catch (PayPalRESTException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 退款
     *
     * @param paymentId 支付id
     * @return boolean
     */
    public boolean refund(String paymentId) {
        LitemallOrder order = orderService.findByOutTradeNo(paymentId);
        return refund(order.getId());
    }

    /**
     * 成功
     *
     * @param payment   付款
     * @param userName  用户名
     * @param memberId  成员身份
     * @param userId    用户id
     * @param paymemtId paymemt id
     * @return {@link Object}
     */
    public Object success(Payment payment, String userName, Integer memberId, Integer userId, String paymemtId) {
        LitemallOrder order = orderService.findByOutTradeNo(paymemtId);
        userId=userId == null?order.getUserId():userId;
        LitemallUser user = litemallUserService.findById(userId);
        if (payment.getState().equals("approved")) {
            LumierePayMember payMember = lumierePayMemberService.findById(memberId);
            //找被赠送人

            //赠送给有账号的用户
            if (StrUtil.isNotBlank(userName)?ObjectUtil.isNotNull(litemallUserService.queryMobileOrEmail(userName)):false) {
                LitemallUser giveeUser = litemallUserService.queryMobileOrEmail(userName);
                //找出付费会员用户表记录
                LumierePayMemberUserExample example = new LumierePayMemberUserExample();
                example.or().andUserNameEqualTo(userName).andPayMemberIdEqualTo(memberId);
                List<LumierePayMemberUser> userList = lumierePayMemberUserService.list(example);
                //是否已拥有付费会员
                if(userList.size() != 0){
                    return ResponseUtil.fail("赠送会员失败，对方已拥有");
                }
                LumierePayMemberUser memberUser = new LumierePayMemberUser();
                LocalDateTime startTime = LocalDateTime.now();
                memberUser.setStartTime(startTime);
                memberUser.setUserName(userName);
                memberUser.setPayMemberId(memberId);
                memberUser.setUserId(giveeUser.getId());
                LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

                if (payMember.getExpiredDays().equals(0)) {
                    endT = null;
                }
                memberUser.setEndTime(endT);
                memberUser.setAddTime(startTime);
                memberUser.setUpdateTime(startTime);
                memberUser.setDeleted(false);
                lumierePayMemberUserService.add(memberUser);

                log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_PAYPAL,
                        Constants.MEMBER_PURCHASE_TYPE_GIVE, payMember.getRenevalMoney(),
                        giveeUser != null ? giveeUser.getId() : null, userId,userName,
                        memberUser.getId(), endT, null);

                logger.debug("赠送----------------------");
                BuyGiveeMemberDTO buyGiveeMemberDto = new BuyGiveeMemberDTO();
                buyGiveeMemberDto.setMessage(order.getMessage());
                buyGiveeMemberDto.setGiveeUser(userName);
                buyGiveeMemberDto.setMemberId(memberId);
                wxPayMemberUserManageService.sendNotificationToExistUser(giveeUser,buyGiveeMemberDto,payMember,user,memberUser,endT);
                return ResponseUtil.ok("赠送会员成功");
            }else if(StrUtil.isNotBlank(userName)?ObjectUtil.isEmpty(litemallUserService.queryMobileOrEmail(userName)):false){
                //赠送给没有账号的用户
                //找出付费会员用户表记录
                LumierePayMemberUserExample example = new LumierePayMemberUserExample();
                example.or().andUserNameEqualTo(userName).andPayMemberIdEqualTo(memberId);
                List<LumierePayMemberUser> userList = lumierePayMemberUserService.list(example);
                //是否已拥有付费会员
                if(userList.size() != 0){
                    return ResponseUtil.fail("赠送会员失败，对方已拥有");
                }

                LumierePayMemberUser memberUser = new LumierePayMemberUser();
                LocalDateTime startTime = LocalDateTime.now();
                memberUser.setStartTime(startTime);
                memberUser.setUserName(userName);
                memberUser.setPayMemberId(memberId);
                memberUser.setUserId(null);
                LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

                if (payMember.getExpiredDays().equals(0)) {
                    endT = null;
                }
                memberUser.setEndTime(endT);
                if(payMember.getEndTime()!=null){
                    memberUser.setEndTime(payMember.getEndTime());
                }
                memberUser.setAddTime(startTime);
                memberUser.setUpdateTime(startTime);
                memberUser.setDeleted(false);
                lumierePayMemberUserService.add(memberUser);

                log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_PAYPAL,
                        Constants.MEMBER_PURCHASE_TYPE_GIVE, payMember.getRenevalMoney(),
                        null, userId,userName,
                        memberUser.getId(), endT, null);

                logger.debug("赠送----------------------");
                BuyGiveeMemberDTO buyGiveeMemberDto = new BuyGiveeMemberDTO();
                buyGiveeMemberDto.setMessage(order.getMessage());
                buyGiveeMemberDto.setGiveeUser(userName);
                buyGiveeMemberDto.setMemberId(memberId);
                wxPayMemberUserManageService.sendNotificationToNotExistUser(payMember,user,buyGiveeMemberDto,endT,memberUser);
                return ResponseUtil.ok("赠送会员成功");
            } else {
                List<LumierePayMemberUser> memberUsers = lumierePayMemberUserService.listUsers(userId, memberId);

                if (memberUsers.size() > 0) {
                    LocalDateTime starT = memberUsers.get(0).getEndTime();
                    LocalDateTime eT = payMember.getExpiredDays() != null ? starT.plusDays(payMember.getExpiredDays()) : null;

                    if (payMember.getExpiredDays().equals(0)) {
                        eT = null;
                    }
                    memberUsers.get(0).setEndTime(eT);
                    if(payMember.getEndTime()!=null){
                        memberUsers.get(0).setEndTime(payMember.getEndTime());
                    }
                    logger.debug("续购-------------------------");
                    log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_PAYPAL,
                            Constants.MEMBER_PURCHASE_TYPE_REBUY, payMember.getRenevalMoney(),
                            userId, userId,memberUsers.get(0).getUserName(), memberUsers.get(0).getId(), eT, null);
                    lumierePayMemberUserService.update(memberUsers.get(0));
                    noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, "Member purchase again", "Member purchase again succeeded", userId, memberUsers.get(0));
                    return ResponseUtil.ok("续购会员成功");
                } else {

                    LumierePayMemberUser memberUser = new LumierePayMemberUser();
                    LocalDateTime startTime = LocalDateTime.now();
                    memberUser.setStartTime(startTime);
                    memberUser.setUserName(user.getUsername());
                    memberUser.setPayMemberId(memberId);
                    LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

                    if (payMember.getExpiredDays().equals(0)) {
                        endT = null;
                    }

                    memberUser.setEndTime(endT);
                    if(payMember.getEndTime()!=null){
                        memberUser.setEndTime(payMember.getEndTime());
                    }
                    memberUser.setAddTime(startTime);
                    memberUser.setUpdateTime(startTime);
                    memberUser.setUserId(user.getId());
                    memberUser.setDeleted(false);

                    lumierePayMemberUserService.add(memberUser);

                    logger.debug("购买------------------------------");
                    log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_PAYPAL,
                            Constants.MEMBER_PURCHASE_TYPE_BUY, payMember.getMoney(),
                            userId, userId,user.getUsername(), memberUser.getId(), endT, null);

                    welfareGift(memberId, null, userName, userId, payMember, endT);
                    noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, "Member purchase", "Member purchase succeeded", userId, memberUser);
                    return ResponseUtil.ok("购买会员成功");
                }
            }
        }
        return "<script type=\"text/javascript\">location.href=\"/\"</script>";
    }

    /**
     * 日志
     *
     * @param payMemberId   付费会员id
     * @param payMemberName 支付成员名
     * @param payType       支付类型
     * @param purchaseType  购买类型
     * @param price         价格
     * @param userId        用户id
     * @param purchaseId    购买id
     * @param memberUserId  会员用户id
     * @param expiredTime   过期时间
     * @param point         点
     */
    public void log(Integer payMemberId, String payMemberName, Byte payType, Byte purchaseType,
                    BigDecimal price, Integer userId, Integer purchaseId,String userName,
                    Integer memberUserId, LocalDateTime expiredTime, BigDecimal point) {
        LumierePayMemberUserLog log = new LumierePayMemberUserLog();
        log.setPayMemberId(payMemberId);
        log.setPayMemberName(payMemberName);
        log.setPayType(payType);
        log.setPurchaseType(purchaseType);
        log.setPrice(price);
        log.setUserId(userId);
        log.setPurchaseId(purchaseId);
        log.setPurchaseName(userName);
        log.setExpiredTime(expiredTime);
        log.setMemberUserId(memberUserId);
        log.setPoint(point);
        log.setAddTime(LocalDateTime.now());
        log.setUpdateTime(LocalDateTime.now());
        log.setDeleted(false);
        lumierePayMemberUserLogService.add(log);
    }

    /**
     * 福利礼品
     * 赠送礼物卡，优惠券，订阅
     *
     * @param memberId  成员身份
     * @param giveeUser givee用户
     * @param userName  用户名
     * @param userId    用户id
     * @param payMember 付费会员
     * @param endT      endt
     */
    public void welfareGift(Integer memberId, LitemallUser giveeUser,
                            String userName, Integer userId, LumierePayMember payMember, LocalDateTime endT) {
        //添加优惠券
        List<LumiereCouponStrategy> couponStrategies = lumiereCouponStrategyService.list(Wrappers.lambdaQuery(LumiereCouponStrategy.class)
                .eq(LumiereCouponStrategy::getCouponType,6)
                .like(LumiereCouponStrategy::getPayMember, payMember.getId()));
        if(couponStrategies!=null&&couponStrategies.size()>0) {
            for (LumiereCouponStrategy lumiereCouponStrategy : couponStrategies) {
                long nextId = IdUtil.getSnowflake(2, 2).nextId();
                LocalDateTime[] localDateTimes = AdminCouponDateUtil.calculateExpirationTime(lumiereCouponStrategy);
                //发放券
                LumiereCouponUser coupon = LumiereCouponUser.builder()
                        .userId(ObjectUtil.isNotNull(giveeUser)?giveeUser.getId():userId)
                        .strategyId(lumiereCouponStrategy.getId())
                        .couponId(lumiereCouponStrategy.getCouponId())
                        .userName(ObjectUtil.isNotNull(giveeUser)?giveeUser.getUsername():litemallUserService.findById(userId).getUsername())
                        .startTime(localDateTimes[0])
                        .endTime(localDateTimes[1])
                        .code(String.valueOf(nextId))
                        .addTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .deleted(false)
                        .build();
                lumiereCouponUserService.save(coupon);
            }
        }
      /*
        List<LumiereMemberWelfareCoupon> welfareCoupons = lumiereMemberWelfareCouponService.findByMemberId(memberId, (byte) 2);

        welfareCoupons.stream().forEach(welfareCoupon -> {
            Integer couponNum = welfareCoupon.getNumbers();
            LitemallCoupon coupon = litemallCouponService.findById(welfareCoupon.getCouponId());

            if (coupon != null) {
                LocalDateTime startT = coupon.getStartTime();
                LocalDateTime endTime = coupon.getEndTime();
                if(coupon.getTimeType().equals((short)0)){
                    startT = LocalDateTime.now();
                    endTime = startT.plusDays(coupon.getDays());
                }

                for (Integer i = 0; i < couponNum; i++) {
                    LitemallCouponUser litemallCouponUser = new LitemallCouponUser();
                    litemallCouponUser.setStartTime(startT);
                    litemallCouponUser.setEndTime(endTime);
                    litemallCouponUser.setStatus((short) 0);
                    litemallCouponUser.setCouponId(coupon.getId());
                    litemallCouponUser.setAddTime(LocalDateTime.now());
                    litemallCouponUser.setUpdateTime(LocalDateTime.now());
                    litemallCouponUser.setDeleted(false);
                    litemallCouponUser.setUserId(giveeUser != null ? giveeUser.getId() : userId);
                    litemallCouponUser.setUserName(userName);
                    litemallCouponUserService.add(litemallCouponUser);
                }
            }
        });*/

        //添加用户订阅
        List<LumiereMemberWelfareSubscribe> welfareSubscribes = lumiereMemberWelfareSubscribeService.findByMemberId(memberId, (byte) 2);

        welfareSubscribes.stream().forEach(welfareSubscribe -> {
            Integer[] selectRuleIds = welfareSubscribe.getSubscribeRuleIds();
            LumiereSubscribeUser subscribeUser = addSubscribeUser(userId, welfareSubscribe.getSubscribeId(), selectRuleIds, endT, userName, giveeUser);
            lumiereSubscribeUserService.add(subscribeUser);
        });


        //添加礼物卡
        if (payMember.getGiftCardIds() != null) {
            Integer[] giftCardIds = payMember.getGiftCardIds();
            for (int i = 0; i < giftCardIds.length; i++) {
                LitemallGiftCard litemallGiftCard = litemallGiftCardService.findById(giftCardIds[i]);
                if (litemallGiftCard != null) {
                    LitemallGiftCardUser giftCardUser = new LitemallGiftCardUser();
                    giftCardUser.setIsDefault(0);

                    String cardNumber = GeneratorUtil.cardNumberGenerator("00", userId);
                    LitemallGiftCardUser cardUser = litemallGiftCardUserService.findByNumber(cardNumber);
                    while (cardUser != null) {
                        cardNumber = GeneratorUtil.cardNumberGenerator("00", userId);
                        cardUser = litemallGiftCardUserService.findByNumber(cardNumber);
                    }
                    giftCardUser.setCardNumber(cardNumber);
                    giftCardUser.setUserId(giveeUser != null ? giveeUser.getId() : userId);
                    giftCardUser.setAmount(BigDecimal.ZERO);
                    giftCardUser.setStatus(0);
                    giftCardUser.setDeleted(false);
                    giftCardUser.setAddTime(LocalDateTime.now());
                    giftCardUser.setUpdateTime(LocalDateTime.now());
                    giftCardUser.setGiftCardId(giftCardIds[i]);
                    litemallGiftCardUserService.add(giftCardUser);
                }
            }
        }

    }

    /**
     * 得到车间区域id
     *
     * @param shopId 商店id
     * @return {@link Integer}
     */
    private Integer getShopRegionId(Integer shopId) {
        List<LitemallShopRegion> litemallShopRegions = litemallShopRegionService.queryByShopId(shopId);
        if (!CollectionUtils.isEmpty(litemallShopRegions)) {
            for (LitemallShopRegion litemallShopRegion : litemallShopRegions) {
                LitemallRegion litemallRegion = regionService.findById(litemallShopRegion.getRegionId());
                if (Constants.REGION_TYPE_CITY == litemallRegion.getType()) {
                    return litemallShopRegion.getRegionId();
                }
            }
        }
        return null;
    }

    /**
     * 余额购买付费会员 （自己给自己买）
     *
     * @param userId   用户id
     * @param memberId 成员身份
     * @param money
     * @return {@link ResponseUtil.Response}
     */
    @Transactional
    public ResponseUtil.Response moneyBuyMember(Integer userId, Integer memberId, BigDecimal money) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        //根据付费会员允许的购买次数判断是否可以购买
        LumierePayMember payMember =  lumierePayMemberService.findById(memberId);
        if (payMember == null) {
            return ResponseUtil.fail(MEMBER_INVALID, "会员不存在");
        }
        Integer count =  lumierePayMemberUserLogService.countMemberUserByMemberId(userId,memberId);

        // 校验礼物卡可购买数量
        for (Integer cardId :payMember.getGiftCardIds()) {
            LitemallGiftCard card = litemallGiftCardService.findById(cardId);
            // 校验礼物卡可购买数量
            Integer saleNum =  (int) litemallGiftCardUserService.sumByCardId(cardId);
            if(card.getNumbers() != 0 && saleNum >= card.getNumbers()){
                return ResponseUtil.fail(CARD_SALED_OVER,"礼物卡已售罄");
            }
        }

        if(payMember.getBuyTimes().equals(0)){
            if(count ==1 ){
                return ResponseUtil.fail(PAYMEMBER_BUY_TIMES_OVER, "用户已购买次数达到该会员购买次数上限");
            }
        }else if(!payMember.getBuyTimes().equals(-1)){
            if(count >= payMember.getBuyTimes()){
                return ResponseUtil.fail(PAYMEMBER_BUY_TIMES_OVER, "用户已购买次数达到该会员购买次数上限");
            }
        }

        //余额购买
        LitemallUser user = litemallUserService.findById(userId);
        //查用户余额
        if(user.getAvailableAmount().compareTo(money)==-1){
            return ResponseUtil.fail(MONEY_BUY_PAY_INSUFFICIENT,"用户余额不足");
        }
        //减余额
        user.setAvailableAmount(user.getAvailableAmount().subtract(money));
        //更新一下用户余额
        litemallUserService.updateById2(user);

        //创建一个余额购买订单
        /*String orderSn = RandomUtil.randomNumbers(16);
        LitemallOrder order = new LitemallOrder();
        order.setOrderSn(orderSn);
        order.setOrderStatus(Constants.ORDER_STATUS_FINISHED);
        order.setConsignee("");
        order.setMobile("");
        order.setMessage("APP paid member consumption");
        order.setAddress("");
        order.setOrderPrice(money);
        order.setFreightPrice(new BigDecimal(0.00));
        order.setCouponPrice(new BigDecimal(0.00));
        order.setIntegralPrice(new BigDecimal(0.00));
        order.setOrderPrice(new BigDecimal(0.00));
        order.setActualPrice(money);
        order.setUserId(userId);
        order.setShopOrder(true);
        order.setPayType(PAY_TYPE_BALANCE);
        order.setPayMemberId(payMember.getId());
        order.setMadeStatus((byte)0);
        order.setMemberId(userId);
        order.setPayTime(LocalDateTime.now());
        // 添加订单表项
        orderService.add(order);*/

        LitemallRechargeConsumption rechargeConsumption = new LitemallRechargeConsumption();
        rechargeConsumption.setUserId(user.getId());
        //rechargeConsumption.setOrderId(order.getId());
        rechargeConsumption.setMobile(StrUtil.isNotEmpty(user.getMobile())?user.getMobile():null);
        rechargeConsumption.setUsername(user.getUsername());
        rechargeConsumption.setUserLevel(user.getUserLevel());
        rechargeConsumption.setAvailableAmount(user.getAvailableAmount());
        rechargeConsumption.setPoints(user.getPoints());
        rechargeConsumption.setType((byte) 2);
        rechargeConsumption.setAmount(money);
        rechargeConsumption.setDeleted(false);
        rechargeConsumption.setAddUserId(userId);
        rechargeConsumption.setOrderSource((byte) 1);
        litemallRechargeConsumptionService.add(rechargeConsumption);

        //判断一下是续购还是新购
        List<LumierePayMemberUser> memberUsers = lumierePayMemberUserService.listUsers(userId, memberId);
        if(memberUsers.size()>0){
            //续购
            LocalDateTime starT = memberUsers.get(0).getEndTime();
            LocalDateTime eT = payMember.getExpiredDays() != null ? starT.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                eT = null;
            }
            if(payMember.getEndTime()!=null){
                memberUsers.get(0).setEndTime(payMember.getEndTime());
            }
            memberUsers.get(0).setEndTime(eT);

            logger.debug("余额续购-------------------------");
            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_YUE,
                    Constants.MEMBER_PURCHASE_TYPE_REBUY, payMember.getRenevalMoney(),
                    userId, userId,memberUsers.get(0).getUserName(), memberUsers.get(0).getId(), eT, null);
            lumierePayMemberUserService.update(memberUsers.get(0));
            noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, "Member purchase again", "Member purchase again succeeded", userId, memberUsers.get(0));
            return ResponseUtil.ok("续购会员成功");
        }else {
            //新购
            LumierePayMemberUser memberUser = new LumierePayMemberUser();
            LocalDateTime startTime = LocalDateTime.now();
            memberUser.setStartTime(startTime);
            memberUser.setUserName(user.getUsername());
            memberUser.setPayMemberId(memberId);
            LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                endT = null;
            }
            memberUser.setEndTime(endT);
            if(payMember.getEndTime()!=null){
                memberUser.setEndTime(payMember.getEndTime());
            }
            memberUser.setAddTime(startTime);
            memberUser.setUpdateTime(startTime);
            memberUser.setUserId(user.getId());
            memberUser.setDeleted(false);
            lumierePayMemberUserService.add(memberUser);
            logger.debug("余额购买------------------------------");
            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_YUE,
                    Constants.MEMBER_PURCHASE_TYPE_BUY, payMember.getMoney(),
                    userId, userId,user.getUsername(), memberUser.getId(), endT, null);

            welfareGift(memberId, user, user.getUsername(), userId, payMember, endT);
            noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, "Member purchase", "Member purchase succeeded", userId, memberUser);
            return ResponseUtil.ok("购买会员成功");
        }
    }

    /**
     * 余额购买付费会员赠送
     *
     * @param userId                 用户id
     * @param buyGiveeMemberDto 余额购买付费会员赠送dto
     * @return {@link ResponseUtil.Response}
     */
    public ResponseUtil.Response moneyBuyGiveeMember(Integer userId,  BuyGiveeMemberDTO buyGiveeMemberDto) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (!RegexUtil.isMobileValid(buyGiveeMemberDto.getGiveeUser()) && !RegexUtil.isEmailExact(buyGiveeMemberDto.getGiveeUser())) {
            return ResponseUtil.fail(AUTH_INVALID_MOBILE, "手机号或邮箱格式不正确");
        }
        //根据付费会员允许的购买次数判断是否可以购买
        LumierePayMember payMember =  lumierePayMemberService.findById(buyGiveeMemberDto.getMemberId());
        if (payMember == null) {
            return ResponseUtil.fail(MEMBER_INVALID, "会员不存在");
        }
        Integer count =  lumierePayMemberUserLogService.countMemberUserByMemberId(userId,buyGiveeMemberDto.getMemberId());

        // 校验礼物卡可购买数量
        for (Integer cardId :payMember.getGiftCardIds()) {
            LitemallGiftCard card = litemallGiftCardService.findById(cardId);
            // 校验礼物卡可购买数量
            Integer saleNum =  (int) litemallGiftCardUserService.sumByCardId(cardId);
            if(card.getNumbers() != 0 && saleNum >= card.getNumbers()){
                return ResponseUtil.fail(CARD_SALED_OVER,"礼物卡已售罄");
            }
        }

        if(payMember.getBuyTimes().equals(0)){
            if(count ==1 ){
                return ResponseUtil.fail(PAYMEMBER_BUY_TIMES_OVER, "用户已购买次数达到该会员购买次数上限");
            }
        }else if(!payMember.getBuyTimes().equals(-1)){
            if(count >= payMember.getBuyTimes()){
                return ResponseUtil.fail(PAYMEMBER_BUY_TIMES_OVER, "用户已购买次数达到该会员购买次数上限");
            }
        }
        //余额购买
        LitemallUser user = litemallUserService.findById(userId);
        //查用户余额
        if(user.getAvailableAmount().compareTo(buyGiveeMemberDto.getMoney())==-1){
            return ResponseUtil.fail(MONEY_BUY_PAY_INSUFFICIENT,"用户余额不足");
        }
        //减余额
        user.setAvailableAmount(user.getAvailableAmount().subtract(buyGiveeMemberDto.getMoney()));
        //更新一下用户余额
        litemallUserService.updateById2(user);
        //创建订单记录
        String orderSn = RandomUtil.randomNumbers(16);
        LitemallOrder litemallOrder = new LitemallOrder();
        litemallOrder.setUserId(userId);
        litemallOrder.setOrderSn(orderSn);
        litemallOrder.setOrderStatus(OrderUtil.STATUS_CONFIRM);
        litemallOrder.setRefundStatus((byte)0);
        litemallOrder.setEvaluationStatus((byte)0);
        litemallOrder.setMemberId(userId);
        litemallOrder.setGoodsPrice(buyGiveeMemberDto.getMoney());
        litemallOrder.setActualPrice(buyGiveeMemberDto.getMoney());
        litemallOrder.setMessage("APP gift card consumption");
        litemallOrder.setPayTime(LocalDateTime.now());
        litemallOrder.setPayType(PAY_TYPE_BALANCE);
        orderService.add(litemallOrder);

        //创建消费记录
       /* litemallOrder =orderService.getOne(Wrappers.lambdaQuery(LitemallOrder.class)
                .eq(LitemallOrder::getUserId,userId).eq(LitemallOrder::getOrderSn,orderSn));*/

        LitemallRechargeConsumption rechargeConsumption = new LitemallRechargeConsumption();
        rechargeConsumption.setUserId(user.getId());
        rechargeConsumption.setOrderId(litemallOrder.getId());
        rechargeConsumption.setMobile(StrUtil.isNotEmpty(user.getMobile())?user.getMobile():null);
        rechargeConsumption.setUsername(user.getUsername());
        rechargeConsumption.setUserLevel(user.getUserLevel());
        rechargeConsumption.setAvailableAmount(user.getAvailableAmount());
        rechargeConsumption.setPoints(user.getPoints());
        rechargeConsumption.setType((byte) 2);
        rechargeConsumption.setAmount(buyGiveeMemberDto.getMoney());
        rechargeConsumption.setDeleted(false);
        rechargeConsumption.setAddUserId(userId);
        rechargeConsumption.setOrderSource((byte) 1);
        litemallRechargeConsumptionService.add(rechargeConsumption);
        //创建一个余额购买订单
        LitemallOrder order = new LitemallOrder();
        order.setOrderSn(orderService.generateOrderSn(userId));
        order.setOrderStatus(Constants.ORDER_STATUS_UNPAID);
        order.setConsignee("");
        order.setMobile("");
        order.setMessage("");
        order.setAddress("");
        order.setOrderPrice(buyGiveeMemberDto.getMoney());
        order.setFreightPrice(new BigDecimal(0.00));
        order.setCouponPrice(new BigDecimal(0.00));
        order.setIntegralPrice(new BigDecimal(0.00));
        order.setActualPrice(buyGiveeMemberDto.getMoney());
        order.setShopOrder(true);
        order.setPayMemberId(payMember.getId());
        order.setMadeStatus((byte)0);
        order.setMemberId(userId);
        order.setUserId(userId);
        // 添加订单表项
        orderService.add(order);
        //分 被赠送用户是否注册
        LitemallUser giveeUser = litemallUserService.queryMobileOrEmail(buyGiveeMemberDto.getGiveeUser());
        if(ObjectUtil.isNotEmpty(giveeUser)){
            //用户存在
            //找出付费会员用户表记录
            LumierePayMemberUserExample example = new LumierePayMemberUserExample();
            example.or().andUserNameEqualTo(buyGiveeMemberDto.getGiveeUser()).andPayMemberIdEqualTo(buyGiveeMemberDto.getMemberId());
            List<LumierePayMemberUser> userList = lumierePayMemberUserService.list(example);
            //是否已拥有付费会员
            if (userList.size() > 0) {
                return ResponseUtil.ok("赠送会员失败，对方已拥有");
            }
            LumierePayMemberUser memberUser = new LumierePayMemberUser();
            LocalDateTime startTime = LocalDateTime.now();
            memberUser.setStartTime(startTime);
            memberUser.setUserName(buyGiveeMemberDto.getGiveeUser());
            memberUser.setPayMemberId(buyGiveeMemberDto.getMemberId());
            memberUser.setUserId(giveeUser.getId());
            LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                endT = null;
            }
            memberUser.setEndTime(endT);
            if(payMember.getEndTime()!=null){
                memberUser.setEndTime(payMember.getEndTime());
            }
            memberUser.setAddTime(startTime);
            memberUser.setUpdateTime(startTime);
            memberUser.setDeleted(false);
            lumierePayMemberUserService.add(memberUser);

            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_YUE,
                    Constants.MEMBER_PURCHASE_TYPE_GIVE, buyGiveeMemberDto.getMoney(),
                    giveeUser != null ? giveeUser.getId() : null, userId,buyGiveeMemberDto.getGiveeUser(),
                    memberUser.getId(), endT, null);

            logger.debug("赠送----------------------");
            //发送通知
            wxPayMemberUserManageService.sendNotificationToExistUser(giveeUser,buyGiveeMemberDto,payMember,user,memberUser,endT);
            return ResponseUtil.ok("赠送会员成功");
        }else {
            //用户不存在
            //赠送给没有账号的用户
            //找出付费会员用户表记录
            LumierePayMemberUserExample example = new LumierePayMemberUserExample();
            example.or().andUserNameEqualTo(buyGiveeMemberDto.getGiveeUser()).andPayMemberIdEqualTo(buyGiveeMemberDto.getMemberId());
            List<LumierePayMemberUser> userList = lumierePayMemberUserService.list(example);
            //是否已拥有付费会员
            if (userList.size() > 0) {
                return ResponseUtil.ok("赠送会员失败，对方已拥有");
            }
            LumierePayMemberUser memberUser = new LumierePayMemberUser();
            LocalDateTime startTime = LocalDateTime.now();
            memberUser.setStartTime(startTime);
            memberUser.setUserName(buyGiveeMemberDto.getGiveeUser());
            memberUser.setPayMemberId(buyGiveeMemberDto.getMemberId());
            memberUser.setUserId(null);
            LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                endT = null;
            }
            if(payMember.getEndTime()!=null){
                memberUser.setEndTime(payMember.getEndTime());
            }
            memberUser.setEndTime(endT);
            memberUser.setAddTime(startTime);
            memberUser.setUpdateTime(startTime);
            memberUser.setDeleted(false);
            lumierePayMemberUserService.add(memberUser);

            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_YUE,
                    Constants.MEMBER_PURCHASE_TYPE_GIVE, buyGiveeMemberDto.getMoney(),
                    null, userId,buyGiveeMemberDto.getGiveeUser(),
                    memberUser.getId(), endT, null);

            logger.debug("赠送----------------------");
            //发送通知
            wxPayMemberUserManageService.sendNotificationToNotExistUser(payMember,user,buyGiveeMemberDto,endT,memberUser);
            return ResponseUtil.ok("赠送会员成功");
        }
    }

    /**
     * 礼物卡购买会员 （给自己买）
     *
     * @param userId               用户id
     * @param giftCardBuyMemberDto 礼物卡购买会员dto
     * @return {@link ResponseUtil.Response}
     */
    public ResponseUtil.Response giftCardBuyMember(Integer userId, GiftCardBuyMemberDTO giftCardBuyMemberDto) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        LitemallUser user = litemallUserService.findById(userId);
        //根据付费会员允许的购买次数判断是否可以购买
        LumierePayMember payMember =  lumierePayMemberService.findById(giftCardBuyMemberDto.getMemberId());
        if (payMember == null) {
            return ResponseUtil.fail(MEMBER_INVALID, "会员不存在");
        }
        Integer count =  lumierePayMemberUserLogService.countMemberUserByMemberId(userId,giftCardBuyMemberDto.getMemberId());

        // 校验礼物卡可购买数量
        for (Integer cardId :payMember.getGiftCardIds()) {
            LitemallGiftCard card = litemallGiftCardService.findById(cardId);
            // 校验礼物卡可购买数量
            Integer saleNum =  (int) litemallGiftCardUserService.sumByCardId(cardId);
            if(card.getNumbers() != 0 && saleNum >= card.getNumbers()){
                return ResponseUtil.fail(CARD_SALED_OVER,"礼物卡已售罄");
            }
        }

        if(payMember.getBuyTimes().equals(0)){
            if(count ==1 ){
                return ResponseUtil.fail(PAYMEMBER_BUY_TIMES_OVER, "用户已购买次数达到该会员购买次数上限");
            }
        }else if(!payMember.getBuyTimes().equals(-1)){
            if(count >= payMember.getBuyTimes()){
                return ResponseUtil.fail(PAYMEMBER_BUY_TIMES_OVER, "用户已购买次数达到该会员购买次数上限");
            }
        }
        //礼物卡购买
        LitemallGiftCardUser giftCardUser = litemallGiftCardUserService.findByNumber(giftCardBuyMemberDto.getPayCardNumber());
        if(giftCardUser.getAmount().compareTo(giftCardBuyMemberDto.getMoney())==-1){
            return ResponseUtil.fail(CARD_MONEY_INSUFFICIENT,"用户礼物余额不足");
        }
        //减礼物卡余额
        giftCardUser.setAmount(giftCardUser.getAmount().subtract(giftCardBuyMemberDto.getMoney()));
        //更新一下礼物卡余额
        litemallGiftCardUserService.updateById2(giftCardUser);

        //创建一个余额购买订单
        LitemallOrder order = new LitemallOrder();
        order.setOrderSn(orderService.generateOrderSn(userId));
        order.setOrderStatus(Constants.ORDER_STATUS_FINISHED);
        order.setCompleteTime(LocalDateTime.now());
        order.setConsignee("");
        order.setMobile("");
        order.setMessage("Gift Card Purchase Membership (Buy for yourself)");
        order.setAddress("");
        order.setOrderPrice(giftCardBuyMemberDto.getMoney());
        order.setFreightPrice(new BigDecimal(0.00));
        order.setCouponPrice(new BigDecimal(0.00));
        order.setIntegralPrice(new BigDecimal(0.00));
        order.setOrderPrice(new BigDecimal(0.00));
        order.setActualPrice(giftCardBuyMemberDto.getMoney());
        order.setUserId(userId);
        order.setShopOrder(true);
        order.setPayMemberId(payMember.getId());
        order.setMadeStatus((byte)0);
        order.setPayType(PAY_TYPE_GIFT_CARD);
        order.setMemberId(userId);
        order.setPayTime(LocalDateTime.now());
        // 添加订单表项
        orderService.add(order);
        //判断一下是续购还是新购
        List<LumierePayMemberUser> memberUsers = lumierePayMemberUserService.listUsers(userId, giftCardBuyMemberDto.getMemberId());
        if(memberUsers.size()>0){
            //续购
            LocalDateTime starT = memberUsers.get(0).getEndTime();
            LocalDateTime eT = payMember.getExpiredDays() != null ? starT.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                eT = null;
            }
            memberUsers.get(0).setEndTime(eT);
            if(payMember.getEndTime()!=null){
                memberUsers.get(0).setEndTime(payMember.getEndTime());
            }
            logger.debug("续购-------------------------");
            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_GIFT_CARD,
                    Constants.MEMBER_PURCHASE_TYPE_REBUY, payMember.getRenevalMoney(),
                    userId, userId,memberUsers.get(0).getUserName(), memberUsers.get(0).getId(), eT, null);
            lumierePayMemberUserService.update(memberUsers.get(0));
            noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, "Member purchase again", "Member purchase again succeeded", userId, memberUsers.get(0));
            return ResponseUtil.ok("续购会员成功");
        }else {
            //新购
            LumierePayMemberUser memberUser = new LumierePayMemberUser();
            LocalDateTime startTime = LocalDateTime.now();
            memberUser.setStartTime(startTime);
            memberUser.setUserName(user.getUsername());
            memberUser.setPayMemberId(giftCardBuyMemberDto.getMemberId());
            LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                endT = null;
            }
            memberUser.setEndTime(endT);
            if(payMember.getEndTime()!=null){
                memberUser.setEndTime(payMember.getEndTime());
            }
            memberUser.setAddTime(startTime);
            memberUser.setUpdateTime(startTime);
            memberUser.setUserId(userId);
            memberUser.setDeleted(false);
            lumierePayMemberUserService.add(memberUser);
            logger.debug("购买------------------------------");
            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_GIFT_CARD,
                    Constants.MEMBER_PURCHASE_TYPE_BUY, payMember.getMoney(),
                    userId, userId,user.getUsername(), memberUser.getId(), endT, null);

            welfareGift(giftCardBuyMemberDto.getMemberId(), user, user.getUsername(), userId, payMember, endT);
            noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, "Member purchase", "Member purchase succeeded", userId, memberUser);
            return ResponseUtil.ok("购买会员成功");
        }
    }

    /**
     * 礼物卡购买会员赠送
     *
     * @param userId                    用户id
     * @param buyGiveeMemberDto 礼品卡购买givee成员dto
     * @return {@link ResponseUtil.Response}
     */
    public ResponseUtil.Response giftCardBuyGiveeMember(Integer userId, BuyGiveeMemberDTO buyGiveeMemberDto) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (!RegexUtil.isMobileValid(buyGiveeMemberDto.getGiveeUser()) && !RegexUtil.isEmailExact(buyGiveeMemberDto.getGiveeUser())) {
            return ResponseUtil.fail(AUTH_INVALID_MOBILE, "手机号或邮箱格式不正确");
        }

        LitemallUser user = litemallUserService.findById(userId);
        //根据付费会员允许的购买次数判断是否可以购买
        LumierePayMember payMember =  lumierePayMemberService.findById(buyGiveeMemberDto.getMemberId());
        if (payMember == null) {
            return ResponseUtil.fail(MEMBER_INVALID, "会员不存在");
        }
        Integer count =  lumierePayMemberUserLogService.countMemberUserByMemberId(userId,buyGiveeMemberDto.getMemberId());

        // 校验礼物卡可购买数量
        for (Integer cardId :payMember.getGiftCardIds()) {
            LitemallGiftCard card = litemallGiftCardService.findById(cardId);
            // 校验礼物卡可购买数量
            Integer saleNum =  (int) litemallGiftCardUserService.sumByCardId(cardId);
            if(card.getNumbers() != 0 && saleNum >= card.getNumbers()){
                return ResponseUtil.fail(CARD_SALED_OVER,"礼物卡已售罄");
            }
        }

        if(payMember.getBuyTimes().equals(0)){
            if(count ==1 ){
                return ResponseUtil.fail(PAYMEMBER_BUY_TIMES_OVER, "用户已购买次数达到该会员购买次数上限");
            }
        }else if(!payMember.getBuyTimes().equals(-1)){
            if(count >= payMember.getBuyTimes()){
                return ResponseUtil.fail(PAYMEMBER_BUY_TIMES_OVER, "用户已购买次数达到该会员购买次数上限");
            }
        }
        //礼物卡购买
        LitemallGiftCardUser giftCardUser = litemallGiftCardUserService.findByNumber(buyGiveeMemberDto.getPayCardNumber());
        if(giftCardUser.getAmount().compareTo(buyGiveeMemberDto.getMoney())==-1){
            return ResponseUtil.fail(CARD_MONEY_INSUFFICIENT,"用户礼物余额不足");
        }
        //减礼物卡余额
        giftCardUser.setAmount(giftCardUser.getAmount().subtract(buyGiveeMemberDto.getMoney()));
        //更新一下礼物卡余额
        litemallGiftCardUserService.updateById2(giftCardUser);

        //创建一个余额购买订单
        LitemallOrder order = new LitemallOrder();
        order.setOrderSn(orderService.generateOrderSn(userId));
        order.setOrderStatus(Constants.ORDER_STATUS_FINISHED);
        order.setCompleteTime(LocalDateTime.now());
        order.setConsignee("");
        order.setMobile("");
        order.setMessage("Gift card purchase member gift");
        order.setAddress("");
        order.setOrderPrice(buyGiveeMemberDto.getMoney());
        order.setFreightPrice(new BigDecimal(0.00));
        order.setCouponPrice(new BigDecimal(0.00));
        order.setIntegralPrice(new BigDecimal(0.00));
        order.setOrderPrice(new BigDecimal(0.00));
        order.setActualPrice(buyGiveeMemberDto.getMoney());
        order.setShopOrder(true);
        order.setPayMemberId(payMember.getId());
        order.setMadeStatus((byte)0);
        order.setMemberId(userId);
        order.setUserId(userId);
        order.setPayType(PAY_TYPE_GIFT_CARD);
        order.setPayTime(LocalDateTime.now());
        // 添加订单表项
        orderService.add(order);
        //分 被赠送用户是否注册
        LitemallUser giveeUser = litemallUserService.queryMobileOrEmail(buyGiveeMemberDto.getGiveeUser());
        if(ObjectUtil.isNotEmpty(giveeUser)){
            //用户存在
            //找出付费会员用户表记录
            LumierePayMemberUserExample example = new LumierePayMemberUserExample();
            example.or().andUserNameEqualTo(buyGiveeMemberDto.getGiveeUser()).andPayMemberIdEqualTo(buyGiveeMemberDto.getMemberId());
            List<LumierePayMemberUser> userList = lumierePayMemberUserService.list(example);
            //是否已拥有付费会员
            if (userList.size() > 0) {
                return ResponseUtil.ok("赠送会员失败，对方已拥有");
            }
            LumierePayMemberUser memberUser = new LumierePayMemberUser();
            LocalDateTime startTime = LocalDateTime.now();
            memberUser.setStartTime(startTime);
            memberUser.setUserName(buyGiveeMemberDto.getGiveeUser());
            memberUser.setPayMemberId(buyGiveeMemberDto.getMemberId());
            memberUser.setUserId(giveeUser.getId());
            LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                endT = null;
            }
            memberUser.setEndTime(endT);
            if(payMember.getEndTime()!=null){
                memberUser.setEndTime(payMember.getEndTime());
            }
            memberUser.setAddTime(startTime);
            memberUser.setUpdateTime(startTime);
            memberUser.setDeleted(false);
            lumierePayMemberUserService.add(memberUser);

            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_GIFT_CARD,
                    Constants.MEMBER_PURCHASE_TYPE_GIVE, buyGiveeMemberDto.getMoney(),
                    giveeUser != null ? giveeUser.getId() : null, userId,buyGiveeMemberDto.getGiveeUser(),
                    memberUser.getId(), endT, null);

            logger.debug("赠送----------------------");
            //发送通知
            wxPayMemberUserManageService.sendNotificationToExistUser(giveeUser,buyGiveeMemberDto,payMember,user,memberUser,endT);
            return ResponseUtil.ok("赠送会员成功");
        }else {
            //用户不存在
            //赠送给没有账号的用户
            //找出付费会员用户表记录
            LumierePayMemberUserExample example = new LumierePayMemberUserExample();
            example.or().andUserNameEqualTo(buyGiveeMemberDto.getGiveeUser()).andPayMemberIdEqualTo(buyGiveeMemberDto.getMemberId());
            List<LumierePayMemberUser> userList = lumierePayMemberUserService.list(example);
            //是否已拥有付费会员
            if (userList.size() > 0) {
                return ResponseUtil.ok("赠送会员失败，对方已拥有");
            }
            LumierePayMemberUser memberUser = new LumierePayMemberUser();
            LocalDateTime startTime = LocalDateTime.now();
            memberUser.setStartTime(startTime);
            memberUser.setUserName(buyGiveeMemberDto.getGiveeUser());
            memberUser.setPayMemberId(buyGiveeMemberDto.getMemberId());
            memberUser.setUserId(null);
            LocalDateTime endT = payMember.getExpiredDays() != null ? startTime.plusDays(payMember.getExpiredDays()) : null;

            if (payMember.getExpiredDays().equals(0)) {
                endT = null;
            }
            memberUser.setEndTime(endT);
            if(payMember.getEndTime()!=null){
                memberUser.setEndTime(payMember.getEndTime());
            }
            memberUser.setAddTime(startTime);
            memberUser.setUpdateTime(startTime);
            memberUser.setDeleted(false);
            lumierePayMemberUserService.add(memberUser);

            log(payMember.getId(), payMember.getName(), Constants.MEMBER_PAY_TYPE_GIFT_CARD,
                    Constants.MEMBER_PURCHASE_TYPE_GIVE,buyGiveeMemberDto.getMoney(),
                    null, userId,buyGiveeMemberDto.getGiveeUser(),
                    memberUser.getId(), endT, null);

            logger.debug("赠送----------------------");
            //发送通知
            wxPayMemberUserManageService.sendNotificationToNotExistUser(payMember,user,buyGiveeMemberDto,endT,memberUser);
            return ResponseUtil.ok("赠送会员成功");
        }
    }
}
